<?php

class Group {

	function __construct($id) {
		$this->id = $id;
		$query = mysql_query("SELECT * FROM `group` WHERE `id` = '$id';") or die(mysql_error());
		$result = mysql_fetch_object($query);
		if($result != '') {
			$this->id = $result->id;
			$this->name = $result->name;
			$this->description = $result->description;
			$this->students = explode(',',$result->students);
			$this->course = $result->course;
			$this->code_url = $result->code_url;
			$this->groups_url = $result->groups_url;
		}
	}

	private function updateGroup() {
		$query = mysql_query("UPDATE `group` SET `name` = '$this->name', `description` = '$this->description', `students` = '$this->students', `course` = '$this->course', `code_url` = '$this->code_url', `groups_url` = '$this->groups_url'") or die(mysql_error());
		return true;
	}
	
	public function getAllStudents() {
		$query = mysql_query("SELECT * FROM `student` WHERE `group` = '$this->id'") or die(mysql_error());
		$r = mysql_fetch_object($query);
		if($r) {
			$students[] = new Student($r->id);
			return $students;
		} else
		return false;
	}
	
	public function getStudent($id) {
		if(count($this->students) == 1) {
			if($id == $this->students) {
				return new Student($this->students);	
			} else { 
				return false;
			}
		} else {
			foreach($this->students as $m) {
				if($m == $id) {
					return new Student($m);
				} else {
					return false;
				}
			}
		}
	}
	
	public function addStudent($data) {
		
	}
	
	public function searchStudent($data) {
		$query = mysql_query("SELECT * FROM `student` WHERE `full_name` LIKE '%$data%' OR `email` LIKE '%$data%' AND `group` = '$this->id'") or die(mysql_error());
		$result = mysql_fetch_object($query);
		if($result)
			return $this->getStudent($result->id);
		else
			$this->addStudent($data);
	}

	public function remove() {
		$this->course = '';
		$this->updateGroup();
		return true;
	}
}